<template>
  <div ref="chartRef" :id="chartId" style="width: 100%; height: 100%;"></div>
</template>

<script setup>
import * as echarts from 'echarts';
import { onMounted, onUnmounted, defineProps, watch, ref } from 'vue';

// 定义接收的 props
const props = defineProps({
  chartData: {
    type: Array,
    default: () => []
  },
  chartId: {
    type: String,
    required: true
  }
});

const chartRef = ref(null);
let myChart;
let resizeObserver;

// 计算柱状图宽度的函数
const calculateBarWidth = () => {
  const minWidth = 16; // 最小宽度，单位为像素
  const maxWidth = 60; // 最大宽度，单位为像素
  const widthPercentage = 2; // 宽度百分比系数
  const windowWidth = window.innerWidth;
  const calculatedWidth = (windowWidth * widthPercentage) / 100;
  return Math.min(Math.max(calculatedWidth, minWidth), maxWidth);
};

const updateChart = () => {
  const companyNames = [];
  const companyPeopleCounts = [];
  for (const { name, value } of props.chartData) {
    companyNames.push(name);
    companyPeopleCounts.push(value);
  }

  const option = {
    tooltip: {
      trigger: 'axis',
      axisPointer: {
        type: 'shadow'
      }
    },
    grid: {
      left: '20%', // 调整 grid 的 left 属性，为纵坐标文字留出更多空间
      right: '10%',
      top: '10%',
      bottom: '10%'
    },
    xAxis: {
      type: 'value',
      axisLine: {
        show: true,
        lineStyle: {
          color: '#666',
          width: 1
        }
      },
      axisTick: {
        show: true,
        lineStyle: {
          color: '#666',
          width: 1
        }
      },
      axisLabel: {
        color: '#5d90ee',
        fontSize: 'clamp(5px, 1vw, 14px)',
        fontWeight: 'bold'
      }
    },
    yAxis: {
      type: 'category',
      data: companyNames,
      axisLine: {
        show: true,
        lineStyle: {
          color: '#666',
          width: 1
        }
      },
      axisTick: {
        show: true,
        lineStyle: {
          color: '#666',
          width: 1
        }
      },
      axisLabel: {
        color: '#5d90ee',
        fontSize: 'clamp(1rem, 1vw, 1.5rem)',
        fontWeight: 'bold',
        margin: 15 // 调整 margin 增加文字与轴线的距离
      }
    },
    legend: {
      textStyle: {
        color: '#5d90ee',
        fontSize: 'clamp(1rem, 1vw, 1.5rem)',
        fontWeight: 'bold'
      }
    },
    series: [
      {
        type: 'bar',
        barWidth: calculateBarWidth(),
        data: companyPeopleCounts
      }
    ]
  };

  if (option && typeof option === 'object') {
    myChart.setOption(option);
  }
};

onMounted(() => {
  const chartDom = chartRef.value;
  if (myChart) {
    myChart.dispose(); // 销毁旧实例
  }
  myChart = echarts.init(chartDom);
  updateChart();

  // 监听窗口大小变化事件
  const handleResize = () => {
    if (myChart) {
      myChart.resize();
      const newBarWidth = calculateBarWidth();
      myChart.setOption({
        series: [
          {
            barWidth: newBarWidth
          }
        ]
      });
    }
  };

  window.addEventListener('resize', handleResize);

  // 监听父级元素高度变化
  resizeObserver = new ResizeObserver(() => {
    if (myChart) {
      myChart.resize();
    }
  });
  resizeObserver.observe(chartDom.parentNode);

  // 在组件卸载时移除事件监听和销毁实例
  onUnmounted(() => {
    window.removeEventListener('resize', handleResize);
    if (resizeObserver) {
      resizeObserver.disconnect();
    }
    if (myChart) {
      myChart.dispose();
      myChart = null;
    }
  });
});

// 监听 chartData 的变化，更新图表
watch(() => props.chartData, () => {
  const chartDom = chartRef.value;
  if (myChart) {
    myChart.dispose(); // 销毁旧实例
  }
  myChart = echarts.init(chartDom);
  updateChart();
});
</script>